<?php

class Client
{
	/**
	 * List of libs that have already been added.
	 * 
	 * Used to avoid duplicates.
	 */
	static protected $libs = array();
	
	/**
	 * List of tags.
	 *
	 * @var array
	 */
	static protected $tags = array();
	
	static public function addLibrary($lib)
	{
		// Make sure each lib is included only once
		if (isset(self::$libs[$lib])) return;
		
		// Create the library (will automatically add blocks)
		self::$libs[$lib] = new GenericClientLibrary($lib);
		self::$libs[$lib]->addTags();
	}
	
	static public function addHeader($header)
	{
		self::$headers[] = $header;
	}
	
	static public function getClientConfig()
	{
		return '';
	}
	
	/**
	 * Automatically includes and configures the Quibbox client side library.
	 */
	static public function addQuibbox()
	{
		$dropScript  = 'var quibboxInitConfig = {';
		$dropScript .= '	uri: "'.Config::get('uri').'",';
		$dropScript .= '};';
		
		Dom::addTag('append:body', '<script type="text/javascript">'.$dropScript.'</script>');
		Client::addLibrary('client/quibbox/quibbox.js');
	}
}

class GenericClientLibrary
{
	protected $file;
	
	public function __construct($file)
	{
		$this->file = $file;
	}
	
	public function addTags()
	{
		if (substr($this->file, 0, 4) == 'http') {
			$url = $this->file;
		} else {
			$url = Url::local($this->file);
		}
		
		$fileExt = substr($this->file, strrpos($this->file, '.')+1);
		switch ($fileExt) {
			case 'js':
				Dom::addTag('append:body', '<script type="text/javascript" src="'.$url.'"></script>');
				break;
			case 'css':
				Dom::addTag('append:head', '<link rel="stylesheet" type="text/css" href="'.$url.'"/>');
				break;
			default:
				Event::log('framework.client', 'Unknown client library extension "'.$fileExt.'", could not generate tag', Event::LOG_ERROR);
		}
	}
}
?>